package com.itheima.filter;
import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.Result;
import com.itheima.utils.MyJwtUtils;
import com.itheima.utils.MyThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

//@WebFilter(urlPatterns = "/*")
//@Component
public class MyLonginFilter implements Filter {

    //@Autowired
    private MyJwtUtils myJwtUtils;
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("浏览器请求了================================================================>");
        /*
        获取令牌访问路径，若是登录，放行
        根据请求头token 获取令牌
        校验令牌是否合法
        */
        HttpServletRequest request=(HttpServletRequest) servletRequest; //转换为HttpServletRequest子接口
        String uri = request.getRequestURI();//获取资源路径
        //request.getRequestURL(); 获取完整路径
        if ("/login".equals(uri)){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        String token = request.getHeader("Token"); //获取令牌
        Map<String, Object> map = myJwtUtils.parseJwt(token);
        if (map==null){
            //令牌不合法或者已过期
            Result result = Result.error("NOT_LOGIN");
            String jsonString = JSONObject.toJSONString(result);
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            response.getWriter().println(jsonString);
            return;
        }
        //合法的情况
        MyThreadLocalUtils.setValue(map);
        filterChain.doFilter(servletRequest,servletResponse);

    }
}
